var tableElem = "LAY-home-cmslist-list";
var tableToolsElem = "LAY-home-cmslist-tools";
var formElem = "LAY-home-cmslist-listform";
var formSubmitElem = "LAY-home-cmslist-listform-submit";
var formUrl = '/home/article/cmslist/listform'
var historyUrl = '/home/article/cmslist/list'
var baseUrl = window.globalConfig.url_cms_list
var searchFormElem = 'LAY-home-cmslist-search-form'
var searchFormSubmitElem = 'LAY-home-cmslist-search-form-submit'

layui.use(['common'], function (common) {
    var $ = layui.$
        , admin = layui.admin
        , view = layui.view
        , table = layui.table
        , form = layui.form
        , router = layui.router()
        , laydate = layui.laydate

    var cat_id = router.search.cat_id

    //页面管理
    var tableItem = table.render({
        elem: `#${tableElem}`
        , lineStyle: 'height: 80px;'
        , url: baseUrl
        , cols: [[
            {type: 'checkbox', fixed: 'left'}
            , {field: 'article_id', width: 100, title: '新闻id', sort: true}
            , {
                field: 'catName',
                title: '分类',
                minWidth: 300,
                templet: "#TPL-dropdown-cmsCat"
            }
            , {field: 'title', title: '标题', minWidth: 250, edit: 'text'}
            , {field: 'urlrewriter', title: '自定义URL', minWidth: 150, edit: 'text'}
            , {
                field: 'is_top', title: '置顶', minWidth: 80, templet: "#ID-table-cms-is_top-switch"
            }
            , {
                field: 'is_best', title: '加精', minWidth: 80, templet: "#ID-table-cms-is_best-switch"
            }
            , {
                field: 'is_hot', title: '热门', minWidth: 80, templet: "#ID-table-cms-is_hot-switch"
            }
            , {
                field: 'is_show', title: '显示', minWidth: 80, templet: "#ID-table-cms-is_show-switch"
            }
            , {field: 'sort_order', title: '排序', edit: 'text'}
            , {title: '操作', minWidth: 220, align: 'center', fixed: 'right', toolbar: `#${tableToolsElem}`}
        ]]
        , page: true
        , limit: 10
        , limits: [10, 15, 20, 25, 30]
        , text: {none: '暂无数据！'}
        , done() {
            common.tableDropdownEditor(
                this,
                window.globalConfig.url_cms_cat_list + "?all=1",
                baseUrl,
                'article_id',
                'cat_id',
                'cat_name',
                'cat_id'
            )

            // 加载下拉列表
            common.tableSearchDropdown(this,
                window.globalConfig.url_cms_cat_list + "?all=1",
                'cat_name',
                'cat_id',
                'catId',
                'dropdown-type'
            );

            form.render(null, searchFormElem);
            form.on(`submit(${searchFormSubmitElem})`, function (data) {
                var field = data.field;
                tableItem.reloadData({url: baseUrl, where: field});
            })

        }
    });

    var active = {
        //添加
        add: function (othis) {
            location.hash = `${formUrl}/cat_id=${cat_id}`;
        }
    };

    $('.layui-btn.layuiadmin-btn-list').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    // 增删改查
    table.on(`tool(${tableElem})`, function (obj) {
        var data = obj.data;
        if (obj.event === "detail") {  // 查看详情

            window.open(window.globalConfig.base_domain + "/" + data.urlrewriter)

        } else if (obj.event === 'del') { // 删除详情
            layer.confirm('确定删除此详情？', function (index) {
                admin.req({
                    url: window.globalConfig.url_cms_list + "/" + data.article_id,
                    type: "DELETE",
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        layer.close(index);
                        tableItem.reloadData();
                    }
                })
            });
        } else if (obj.event === 'edit') {// 修改详情
            location.hash = `${formUrl}/id=` + data.article_id;
        } else if (obj.event === 'copy') {// 修改详情
            layer.confirm('确定复制此新闻？', function (index) {
                var field = data
                field.title = field.title + "_" + common.generateRandomRewriteUrl(4)
                field.urlrewriter = common.generateRandomRewriteUrl()
                delete field.article_id
                admin.req({
                    url: baseUrl,
                    type: "POST",
                    data: field,
                    success: function (res) {
                        common.ctmMsg(res.code, res.msg)
                        if (res.code === 0) {
                            tableItem.reloadData()
                        }
                    }
                })
            });
        }
    });

    // 表单模块
    layui.data.done = function (d) {
        var data = d.data
        var remoteData = d.data
        layui.use(['form'], function () {

            form.render(null, formElem); //渲染该模板下的动态表单
            if (remoteData.cmsCat) {
                $("#catName").val(remoteData.cmsCat.cat_name);
            } else {
                $("#urlrewriter").val(common.generateRandomRewriteUrl());
            }
            $(".size-suggest").text(sessionStorage.getItem("size_suggest"));
            sessionStorage.removeItem("size_suggest");

            // 日期时间选择器 - 日期和时间选择器同时显示（全面板）
            laydate.render({
                elem: '#ID-laydate-news-showtime',
                type: 'datetime',
                fullPanel: true // 2.8+
            });

            // 加载下拉列表
            common.formDropdownEditor(
                `${window.globalConfig.url_cms_cat_list}?all=1`,
                "catName",
                "catId",
                "catName",
                "cat_id",
                "cat_name"
            )


            // 加载上传插件
            common.uploader('ID-upload-mobile-ico-btn', 'ID-upload-photo-img', 'photo')

            // 加载编辑器
            let editors = {
                'editor': 'content',
            }
            common.loadEditors(remoteData, editors)


            // 表单提交
            form.on(`submit(${formSubmitElem})`, function (data) {
                var field = data.field; //获取提交的字段
                field.is_top = field.is_top === undefined ? 0 : field.is_top;
                field.is_best = field.is_best === undefined ? 0 : field.is_best;
                field.is_hot = field.is_hot === undefined ? 0 : field.is_hot;
                field.is_show = field.is_show === undefined ? 0 : field.is_show;

                field = common.getEditorsContent(field, editors)

                let url = window.globalConfig.url_cms_list;
                let type = "POST";
                if (field.article_id) {
                    url += "/" + field.article_id;
                    type = "PUT"
                }

                //提交 Ajax 成功后，关闭当前弹层并重载表格
                admin.req({
                    url: url,
                    type: type,
                    data: field,
                    success: function (res) {
                        if (res.code === 0) {
                            location.hash = `${historyUrl}/cat_id=${layui.router().search.cat_id}`
                        }
                        layer.msg(res.msg)
                    }
                })

            });
        });
    };

    // 表格文本修改
    common.tableTextEditor(tableElem, baseUrl, 'article_id')


    // 表格的切换器修改
    common.tableSwitchEditor('cms-is_top-status', window.globalConfig.url_cms_list)
    common.tableSwitchEditor('cms-is_best-status', window.globalConfig.url_cms_list)
    common.tableSwitchEditor('cms-is_hot-status', window.globalConfig.url_cms_list)
    common.tableSwitchEditor('cms-is_show-status', window.globalConfig.url_cms_list)
})